/**
 * 
 */
package com.bridgetree.jubaocrm.ui.groups;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.Groups;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Mmember;
/**
 * GroupsAnnouncementActivity
 * </p>
 * 小组成员子菜单内容 2014-5-20 上午11:21:00 create
 * 
 * @since 1.0
 */
public class GroupsMemberChildActivity extends Activity {
	private final String TAG ="GroupsAnnouncementActivity";
	private Context mContext;
	private Groups mGroups;
	private String title="";
	private String type="";
	private String user_id =""; 
	private String token ="";
	private ArrayList<Mmember> mMmemberList;
	private GroupMember1Adapter mRuAdapter2;
	private ListView firstcategory2 = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_members);
		mContext =  this;
		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_bi_tv_title =(TextView)findViewById(R.id.xm_bi_tv_title);
		if(intent.getExtras()!=null){
			mGroups = (Groups)intent.getExtras().getSerializable("groupsMain");
			title = intent.getExtras().getString("title");
			type = intent.getExtras().getString("type");
			xm_bi_tv_title.setText(title);
		}
		
		System.out.println("type:"+type);
		
		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		firstcategory2 = (ListView)findViewById(R.id.groups_lv);
		getGroupsGongGao();
	}
	
	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}
	
	/**
	 * 获取数据1
	 * 
	 * @param pageIndex
	 */
	private void getGroupsGongGao() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");
//			http://crmsoap.woniuwo.cn/info?t=group&p=1&gid=5374743fd5ac700e4ce8f60b&user_id=cd34350bb2844077bfbd4abe5ec56f99&token=15f4b0826dc841198c30088f4a7afd90&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
			String URL = Network.API_DOMAIN + "/group?id=" + mGroups.getGroup_id()+"&r="+type+ "&user_id=" + user_id
			+ "&token=" + token + "&validation="
			+ CRMUserBaseInfo.kValication;
			//http://crmsoap.woniuwo.cn/group?id=5374743fd5ac700e4ce8f60b&r=members&user_id=cd34350bb2844077bfbd4abe5ec56f99&token=15f4b0826dc841198c30088f4a7afd90&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl


			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("获取"+title+"的数据 response=" + response);
							try {
								if (!response.isNull("members")) {
									String data = response.getString("members");
									if (data.equals("[]")) {
										Toast.makeText(mContext, "已经到最后了~",
												Toast.LENGTH_SHORT).show();
									} else {
										org.json.JSONArray jsonArr;
										jsonArr = response.getJSONArray("members");
										mMmemberList = new ArrayList<Mmember>();
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr
											.length(); i++) {
												Mmember mMmember = new Mmember();
												JSONObject jsonObj2 = jsonArr
												.getJSONObject(i);
												if (!jsonObj2.isNull("user_id")) {
													String user_id = jsonObj2
													.getString("user_id");
													mMmember.setUser_id(user_id);
												}
												if (!jsonObj2.isNull("fullname")) {
													String fullname = jsonObj2
													.getString("fullname");
													mMmember.setFullname(fullname);
												}
												mMmemberList.add(mMmember);
											}
										}
										mRuAdapter2 = new GroupMember1Adapter(mContext, mMmemberList);
										firstcategory2.setAdapter(mRuAdapter2);
									}
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}
	
}

class GroupMember1Adapter extends BaseAdapter {
	private List<Mmember>  Date = null;
	private Context context;
	private LayoutInflater mInflater;
	public HashMap<Integer, Bitmap> cachedBitmap;
	private String user_id =""; 
	private String token ="";
	private int index;
	private class GridHolder {
		ImageView xm_12_item_iv;
		TextView xm_12_item_tv;
	}
	
	@SuppressLint("UseSparseArrays")
	public GroupMember1Adapter(Context mContext,List<Mmember> mAnnouncementList) {
		super();
		this.context = mContext;
		this.Date = mAnnouncementList;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
	}

	public int getCount() {
		return Date.size();
	}

	@Override
	public Object getItem(int index) {
		return Date.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(final int index, View convertView, ViewGroup parent) {
		GridHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.xm_12_item, null);
			holder = new GridHolder();
			holder.xm_12_item_iv = (ImageView) convertView.findViewById(R.id.xm_12_item_iv);
			holder.xm_12_item_tv = (TextView) convertView.findViewById(R.id.xm_12_item_tv);
			convertView.setTag(holder);
		} else {
			holder = (GridHolder) convertView.getTag();
		}
		
		final String xm_txt=Date.get(index).getFullname();
		holder.xm_12_item_tv.setText(xm_txt);
		holder.xm_12_item_iv.setVisibility(View.GONE);
//		boolean xm_flag=Date.get(index).getIs_done();
////		if(xm_flag){
//			holder.xm_12_flag_iv.setVisibility(View.INVISIBLE);
////		}else{
////			holder.xm_12_flag_iv.setVisibility(View.VISIBLE);
////		}
		
		convertView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				getCompanyGongGao(Date.get(index).getId(),index);
			}
		});
		return convertView;
	}
	
}
